package com.project.aspect;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Field;

@Component
@Aspect
public class ServiceAspect {
    private static SqlSessionFactory factory;
    static {
        try {
            Reader r = Resources.getResourceAsReader("mybatis.cfg.xml");
            factory = new SqlSessionFactoryBuilder().build(r);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Around("execution(* com.project.service..*.*(..))")
    public Object around(ProceedingJoinPoint pj){
        SqlSession session = factory.openSession();
        try {
            Object targetObj = pj.getTarget();
            Field[] fieldArray = targetObj.getClass().getDeclaredFields();
            for (Field f : fieldArray){
                if (f.getType().isInterface()){
                    f.setAccessible(true);
                    Object mapperObj = session.getMapper(f.getType());
                    f.set(targetObj,mapperObj);
                }
            }
            Object returnObj = pj.proceed();
            session.commit();
            return returnObj;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            session.rollback();
        }finally {
            session.close();
        }
        return null;
    }
}
